import express from 'express';
import { executeSql, prisma } from '../service/mysql.js';
import { logger, dayjs } from '../tools/index.js';
const router = express.Router();

const mergeAccounts = (accounts, sourceBooks) => {
    const sameAccountAggList = [];
    const result = [];
    accounts.forEach(account => {
        const sameAccountAggObj = sameAccountAggList.find(item => item.book_id === account.book_id && item.create_account_no === account.create_account_no);
        if (sameAccountAggObj) {
            sameAccountAggObj.items.push(account);
        } else {
            sameAccountAggList.push({
                book_id: account.book_id,
                create_account_no: account.create_account_no,
                items: [account]
            })
        }
    });
    sameAccountAggList.forEach(sameAccountAggObj => {
        const sameItems = sameAccountAggObj.items;
        if (sameItems.length === 1) {
            result.push(sameItems[0]);
        } else {
            result.push({
                book_id: sameAccountAggObj.book_id,
                create_account_no: sameAccountAggObj.create_account_no,
                create_account_name: sameItems.sort((a, b) => b._max.id - a._max.id)?.[0].create_account_name,
                _count: {
                    id: sameItems.map(item => item._count.id).reduce((a, b) => a + b, 0)
                }
            });
        }
    });
    // 如果 result 没有账户信息，则用微信获取的账户信息进行补充
    // sourceBooks.forEach(book => {
    //     if (book.users) {
    //         const accountItems = result.find(item => item.book_id === book.book_id);
    //         book.users.forEach(bookUser => {
    //             const hasWxUser = accountItems.some(account => account.create_account_no === bookUser.id);
    //             if (!hasWxUser) {
    //                 result.push({
    //                     book_id: book.book_id,
    //                     create_account_no: bookUser.id,
    //                     create_account_name: bookUser.name,
    //                     _count: {
    //                         id: 0
    //                     }
    //                 });
    //             }
    //         })
    //     }
    // });
    return result;
}

router.get('/funds-options', async (req, res, next) => {
    const currentAccountNo = req.context.accountNo;
    const wechatRobot = req.app.locals.wechatRobot;
    let books = [];
    try {
        // 优先从微信中获取账本信息
        const rooms = await wechatRobot.getUserRooms(currentAccountNo);
        books = rooms.map(room => ({
            book_id: room.wxid,
            book_name: room.nick,
            users: room.users.map(user => {
                return {
                    id: user.wxid,
                    name: user.nick
                }
            })
        }));
    } catch (err) {
        logger.error('wechat get books error, %s', err);
        // 降级从数据库获取账本信息
        books = await prisma.t_transaction.groupBy({
            by: ['book_id', 'book_name'],
            where: {
                create_account_no: currentAccountNo
            }
        });
    }
    
    logger.info(`query books = ${JSON.stringify(books)}`);
    if (books.length === 0) {
        return res.json({
            success: true,
            message: '',
            data: []
        });
    }

    const accounts = await prisma.t_transaction.groupBy({
        by: ['book_id', 'create_account_no', 'create_account_name'],
        _count: {
            id: true,
        },
        _max: {
            id: true
        },
        where: {
            book_id: {
                in: books.map(book => book.book_id)
            }
        }
    });
    const tags = await prisma.t_transaction_tags.groupBy({
        by: ['book_id', 'tag'],
        _count: {
            id: true
        },
        where: {
            book_id: {
                in: books.map(book => book.book_id)
            }
        }
    });

    const distinctMonths = await executeSql(`SELECT DISTINCT DATE_FORMAT(create_time, '%Y-%m') AS distinct_month FROM t_transaction WHERE book_id IN (${books.map(book => `'${book.book_id}'`).join(',')});`);
    const sourceBooks = JSON.parse(JSON.stringify(books));
    res.json({
        success: true,
        message: '',
        data: books.map(book => {
            return {
                value: book.book_id,
                label: book.book_name || '未命名',
                options: [
                    {
                        value: 'accountNo',
                        label: '账号',
                        options: mergeAccounts(accounts, sourceBooks)
                            .filter(item => book.book_id === item.book_id)
                            .sort((a, b) => b._count.id - a._count.id)
                            .map(item => ({ value: item.create_account_no, label: item.create_account_name, avatarUrl: `https://sg-funds-center.oss-cn-hangzhou.aliyuncs.com/funds/gpt/${item.create_account_no}.jpg`, count: item._count.id }))
                            .filter(item => item.value)
                    },
                    {
                        value: 'tag',
                        label: '标签',
                        options: tags.filter(item => book.book_id === item.book_id)
                            .sort((a, b) => b._count.id - a._count.id)
                            .map(item => ({ value: item.tag, label: item.tag, count: item._count.id }))
                            .filter(item => item.value)
                    },
                    {
                        value: 'month',
                        label: '月份',
                        options: distinctMonths.map(item => ({ value: item.distinct_month, label: dayjs(item.distinct_month, 'YYYY-MM').format('YYYY年MM月') })).filter(item => item.value)
                    },
                ]
            }
        })
    });
});

export default router;